﻿using System.Configuration;

namespace TimDeal.Configuration
{
    public abstract class CustomConfigurationCollection<T> : ConfigurationElementCollection where T : CustomConfigurationElement, new()
    {
        // ReSharper disable once InconsistentNaming
        protected abstract string ELEMENT_NAME { get; }

        protected override ConfigurationElement CreateNewElement()
        {

            return new T();

        }

        protected override object GetElementKey(ConfigurationElement element)
        {

            return ((T)element).Name;

        }

        public override ConfigurationElementCollectionType CollectionType
        {

            get { return ConfigurationElementCollectionType.BasicMap; }

        }

        protected override string ElementName
        {

            get { return ELEMENT_NAME; }

        }

        protected override bool IsElementName(string elementName)
        {
            return elementName == ELEMENT_NAME;
        }

        public T this[int index]
        {

            get { return (T)BaseGet(index); }

            set
            {

                if (BaseGet(index) != null)
                {

                    BaseRemoveAt(index);

                }

                BaseAdd(index, value);

            }
        }
        
        public new T this[string key]
        {

            get { return (T)BaseGet(key); }

            set
            {

                if (BaseGet(key) != null)
                {

                    BaseRemove(key);

                }

                BaseAdd(value);

            }
        }
    }

    public abstract class CustomConfigurationElement : ConfigurationElement
    {
        [ConfigurationProperty("name")]
        public string Name
        {
            get { return (string)this["name"]; }
        }
    }

}
